package com.fingard.dsp.bank.directbank.chinaums01;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fingard.constant.Format;
import com.fingard.dsp.bank.directConfig.ActSetItem;
import com.fingard.dsp.bank.directbank.bankInterface.IGateway;
import com.fingard.dsp.bank.reqrespobj.gateway.ReqGateway;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.ReqQueryOrder;
import com.fingard.dsp.bank.reqrespobj.unifiedorder.RetAtsQueryOrder;
import com.fingard.text.StringHelper;
import com.fingard.text.XmlHelper;
import org.bouncycastle.util.encoders.Base64;

import java.util.Date;
import java.util.HashMap;

/**
 * 中国银联网关支付
 *
 * @author fanh
 * @date 2020年4月9日
 */
public class ChinaUMS01Gateway extends ChinaUMS01Base implements IGateway {

	@Override
	public HashMap<String, String> GenGwMap(ReqGateway p_reqGateway) throws Exception {
		HashMap<String, String> tmpRetMap = new HashMap<String, String>();
		try {
			String ownAct = p_reqGateway.reqHashMap.get("OurBankAccount");
			ActSetItem actItem = getBankConfig().getActSetItem(ownAct, "unifiedorder");
			if (actItem != null) {
				JSONObject submitH5 = new JSONObject();
				submitH5.put("requestTimestamp", Format.DateTime14Format.format(new Date()));

				String srcReserve = "";
				if ("1".equals(p_reqGateway.reqHashMap.get("RealNameFlag")) && "0".equals(p_reqGateway.reqHashMap.get("RealNameType"))) {
					JSONObject srcReserveJson = new JSONObject();
					srcReserveJson.put("payNo", p_reqGateway.reqHashMap.get("RdSeq"));
					srcReserveJson.put("authFlag", "TRUE");
					srcReserveJson.put("authMode", "CIITC");
					srcReserveJson.put("authTransId", p_reqGateway.reqHashMap.get("PaymentNo"));
					srcReserveJson.put("merInstId", actItem.inMerchantId);
					srcReserveJson.put("version", "1.0");
					srcReserve = JSON.toJSONString(srcReserveJson);
					submitH5.put("srcReserve", srcReserve);
				}

				submitH5.put("merOrderId", p_reqGateway.reqHashMap.get("RdSeq"));
				submitH5.put("mid", actItem.merchantId);
				submitH5.put("tid", actItem.termId);
				submitH5.put("instMid", "YUEDANDEFAULT");

				JSONObject goodsObj = new JSONObject();
				goodsObj.put("goodsName", XmlHelper.encode(p_reqGateway.reqHashMap.get("Description")));
				goodsObj.put("body", XmlHelper.encode(p_reqGateway.reqHashMap.get("Attach")));
				JSONArray goodsArray = new JSONArray();
				goodsArray.add(goodsObj);
				submitH5.put("goods", JSON.toJSON(goodsArray));

				submitH5.put("attachedData", XmlHelper.encode(p_reqGateway.reqHashMap.get("Attach")));
				submitH5.put("orderDesc", XmlHelper.encode(p_reqGateway.reqHashMap.get("Description")));
				submitH5.put("totalAmount", StringHelper.amountMultiply100(p_reqGateway.reqHashMap.get("Amount")));
				submitH5.put("notifyUrl", actItem.notifyURL);
				submitH5.put("returnUrl", actItem.returnURL);

				boolean limitPay = getBankConfig().getValueAsBool("limitPay");
				submitH5.put("limitCreditCard", limitPay+"");

				String bankFrontUrl = bankFront.getUrl("gatewayPay");
				if ("1".equals(p_reqGateway.reqHashMap.get("RealNameFlag")) && "2".equals(p_reqGateway.reqHashMap.get("RealNameType"))) {
					submitH5.put("fixBuyer", "T");
					submitH5.put("fixInsurance", "SZ");
					submitH5.put("paymentInstitution", p_reqGateway.reqHashMap.get("PaymentInstitution"));
					submitH5.put("companyIdInsurance", p_reqGateway.reqHashMap.get("CorpNo"));
					submitH5.put("insuranceNumber", p_reqGateway.reqHashMap.get("InsuPolicyNum"));
					submitH5.put("name", Base64.toBase64String(p_reqGateway.reqHashMap.get("OppActName").getBytes(getCharset())));
					submitH5.put("mobile", Base64.toBase64String(p_reqGateway.reqHashMap.get("CellPhone").getBytes(getCharset())));
					submitH5.put("certType", convertCertTypeToBank(p_reqGateway.reqHashMap.get("CertType")));
					submitH5.put("certNo", Base64.toBase64String(p_reqGateway.reqHashMap.get("CertNumber").getBytes(getCharset())));
					bankFrontUrl = bankFront.getUrl("gatewaySZPay");
					if (StringHelper.isNullOrEmpty(bankFrontUrl)) {
						bankFrontUrl = actItem.serverURLMap.get("gatewaySZPay");
					}
				}
                if ("1".equals(p_reqGateway.reqHashMap.get("RealNameFlag")) && "1".equals(p_reqGateway.reqHashMap.get("RealNameType"))) {
                    submitH5.put("fixInsurance", "SH");
                    submitH5.put("paymentInstitution", p_reqGateway.reqHashMap.get("PaymentInstitution"));
                    submitH5.put("companyIdInsurance", p_reqGateway.reqHashMap.get("CorpNo"));
                    String insNum =  p_reqGateway.reqHashMap.get("SHTradeNo");
                    if (StringHelper.isNullOrEmpty(insNum)) {
                    	insNum = p_reqGateway.reqHashMap.get("CircPaymentNo");
					}
					insNum = insNum.substring(insNum.length()-10);
                    submitH5.put("insuranceNumber", insNum);
                    submitH5.put("name", Base64.toBase64String(p_reqGateway.reqHashMap.get("OppActName").getBytes(getCharset())));
                    submitH5.put("mobile", Base64.toBase64String(p_reqGateway.reqHashMap.get("CellPhone").getBytes(getCharset())));
                    submitH5.put("certType", convertCertTypeToBank(p_reqGateway.reqHashMap.get("CertType")));
                    submitH5.put("certNo", Base64.toBase64String(p_reqGateway.reqHashMap.get("CertNumber").getBytes(getCharset())));
                    bankFrontUrl = bankFront.getUrl("gatewaySHPay");
                    if (StringHelper.isNullOrEmpty(bankFrontUrl)) {
                        bankFrontUrl = actItem.serverURLMap.get("gatewaySHPay");
                    }
                }
				String result = submitSend(bankFrontUrl, JSON.toJSONString(submitH5), actItem);
				if (result.length() > 0) {
					tmpRetMap.put("Result", result);
					tmpRetMap.put("RespCode", "0");
					tmpRetMap.put("RespInfo", "签名成功");
				} else {
					tmpRetMap.put("RespCode", "-1");
					tmpRetMap.put("RespInfo", "签名失败");
				}
			} else {
				tmpRetMap.put("RespCode", "0");
				tmpRetMap.put("RespInfo", "未找到账号:[" + ownAct + "]商户配置信息!");
				tmpRetMap.put("Result", "");
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			tmpRetMap.put("RespCode", "-1");
			tmpRetMap.put("RespInfo", ex.getMessage());
			WriteBankLogLn(ex);
		}
		return tmpRetMap;
	}

	@Override
	public RetAtsQueryOrder queryGWPay(ReqQueryOrder p_reqGateway) throws Exception {
		RetAtsQueryOrder retAts = new RetAtsQueryOrder();
		retAts.rdSeq = p_reqGateway.rdSeq;
		try {
			ActSetItem actItem = this.getBankConfig().getActSetItem(p_reqGateway.ownAct, "unifiedorder");
			if (actItem != null) {
				JSONObject queryH5 = new JSONObject();
				queryH5.put("requestTimestamp", Format.DateTimeFormat.format(new Date()));
				queryH5.put("mid", actItem.merchantId);
				queryH5.put("merOrderId", p_reqGateway.rdSeq);
				queryH5.put("tid", actItem.termId);
				queryH5.put("instMid", "YUEDANDEFAULT");

                String bankFrontUrl = actItem.serverURLMap.get("gatewaySZPayQuery");
                if (StringHelper.isNullOrEmpty(bankFrontUrl)) {
                	bankFrontUrl = bankFront.getUrl("gatewayPayQuery");
				}
				String tmpStrRet = querySend(bankFrontUrl, JSON.toJSONString(queryH5), actItem);
				if (StringHelper.hasAnyChar(tmpStrRet)) {
					if (tmpStrRet.contains("{")) {
						JSONObject tmpJsonResp = JSON.parseObject(tmpStrRet);
						retAts.respCode = "0";
						retAts.respInfo = tmpJsonResp.getString("errMsg");
						String status = tmpJsonResp.getString("status");
						if(status!= null){
							retAts.transState = status;
							retAts.payInfoCode = tmpJsonResp.getString("errCode");
							retAts.outTransID = tmpJsonResp.getString("targetOrderId");
							retAts.oppAct = tmpJsonResp.getString("bankCardNo");
							retAts.oppBank = tmpJsonResp.getString("bankInfo");
						}else{
							retAts.transState = tmpJsonResp.getString("errCode");
							retAts.payInfoCode = tmpJsonResp.getString("errCode");
						}
					} else {
						retAts.respCode = "-1";
						retAts.respInfo = "银联响应数据格式非法";
					}
				} else {
					retAts.respCode = "-1";
					retAts.respInfo = "银联响应为空";
				}
			} else {
				retAts.respCode = "-1";
				retAts.respCode = "未找到账号[" + p_reqGateway.ownAct + "]商户配置信息!";
			}
		} catch (Exception ex) {
			ex.printStackTrace();
			retAts.respCode = "-1";
			retAts.respInfo = ex.getMessage();
			WriteBankLogLn(ex);
		}

		return retAts;
	}
}

